package com.ipt.frm.pw;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileUpload;

/**
 * Servlet implementation class ServletFormRequest
 */
public class ServletFormRequest extends ServletMaestro {
	private static final long serialVersionUID = 1L;
	
	 // location to store file uploaded
    private static final String UPLOAD_DIRECTORY = "upload";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletFormRequest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}
	
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
	
	

	 response.setContentType("text/plain;charset=UTF-8");
     PrintWriter out = response.getWriter();
     try {
         // first check if the upload request coming in is a multipart request
         boolean isMultipart = FileUpload.isMultipartContent(request);
         log("content-length: " + request.getContentLength());
         log("method: " + request.getMethod());
         log("character encoding: " + request.getCharacterEncoding());

         if (isMultipart) {
             DiskFileUpload upload = new DiskFileUpload();
             List items = null;

             try {
                 // parse this request by the handler
                 // this gives us a list of items from the request
                 items = upload.parseRequest(request);
                 log("items: " + items.toString());
             } catch (FileUploadException ex) {
                 log("Failed to parse request", ex);
             }
             Iterator itr = items.iterator();

             while (itr.hasNext()) {
                 FileItem item = (FileItem) itr.next();

                 // check if the current item is a form field or an uploaded file
                 if (item.isFormField()) {

                     // get the name of the field
                     String fieldName = item.getFieldName();
                     String fieldValue = item.getString();
                     //guardamos en la ruquest cada campo con nombre y valor
                     request.setAttribute(fieldName,fieldValue);
                     
                     // if it is name, we can set it in request to thank the user
                     if (fieldName.equals("name")) {
                         out.print("Thank You: " + item.getString());
                     }

                 } else {

                     // the item must be an uploaded file save it to disk. Note that there
                     // seems to be a bug in item.getName() as it returns the full path on
                     // the client's machine for the uploaded file name, instead of the file
                     // name only. To overcome that, I have used a workaround using
                     // fullFile.getName().
                     File fullFile = new File(item.getName());
                     File savedFile = new File(getServletContext().getRealPath("/TEMP"), fullFile.getName());
                     
                     request.setAttribute("nombrefichero",fullFile.getName());
                     request.setAttribute("archivoguardado", "el archivo se ha alojdo en el servidor");
                     request.setAttribute("urlFichero", "http://localhost:8080/PruebasWeb/TEMP/" + fullFile.getName());
                     RequestDispatcher dispacher = this.getServletContext().getRequestDispatcher("/formularioAcuseDeRecibo.jsp");
             		 dispacher.forward(request, response);
             		 
                     try {
                         item.write(savedFile);
                     } catch (Exception ex) {
                         log("Failed to save file", ex);
                     }
                 }
             }

         }
     } finally {
         out.close();  
     }
	
		
	//	String campo1 = request.getParameter("campo1");
	//	String campo2 = request.getParameter("campo2");
	//	String campo3 = request.getParameter("campo3");
		
//		request.setAttribute("campo1", campo1);
	//	request.setAttribute("campo2", campo2);
		//request.setAttribute("campo3", campo3);
		
		
		
		
	}

}
